package cmd

import (
	"bytes"
	"os/exec"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

// ExecuteCmdAndFixEncoding 执行命令并修复中文乱码
func ExecuteCmdAndFixEncoding(name string, arg ...string) (string, error) {
	cmd := exec.Command(name, arg...)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return "", err
	}

	// 将命令行输出的GBK编码转换为UTF-8
	fixedOutput, err := convertCmdOutputToUTF8(out.Bytes())
	if err != nil {
		return "", err
	}

	return fixedOutput, nil
}

// convertCmdOutputToUTF8 将命令行执行结果从GBK转换为UTF-8
func convertCmdOutputToUTF8(rawOutput []byte) (string, error) {
	decoder := simplifiedchinese.GBK.NewDecoder()
	decodedOutput, _, err := transform.Bytes(decoder, rawOutput)
	if err != nil {
		return "", err
	}
	return string(decodedOutput), nil
}
